package com.zqh.elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.zqh.elasticsearch.service.ElasticSearchService;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.rowbeans.doc.ProductDocument;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-02-18 2:19
 */
@Slf4j
@Service("elasticSearchService")
public class ElasticSearchServiceImpl implements ElasticSearchService{
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public Result searchProduct(String key, Integer pageNum, Integer pageSize) {
        SearchRequest searchRequest = new SearchRequest("myfmmall_product");
        ArrayList<ProductDocument> productDocuments = new ArrayList<>();
        HashMap<String, Object> dataMap = new HashMap<>();
        //使用match查询，并进行分页，排序，高亮
        searchRequest.source().query(QueryBuilders.matchQuery("all",key));
        searchRequest.source().from((pageNum - 1) * pageSize).size(pageSize);
        searchRequest.source().sort("soldNum", SortOrder.DESC).sort("productSkuLowestPrice",SortOrder.ASC);
        searchRequest.source().highlighter(new HighlightBuilder().field("productName").requireFieldMatch(false));
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.warn("es搜索商品异常："+e);
            return Result.internalServerError();
        }
        //结果解析
        SearchHits searchHits = searchResponse.getHits();
        dataMap.put("total",searchHits.getTotalHits().value);
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            ProductDocument productDocument = JSON.parseObject(hit.getSourceAsString(), ProductDocument.class);
            productDocuments.add(productDocument);
            //解析高亮数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlightField = highlightFields.get("productName");
            if (highlightField != null) {
                String highlightProductName = highlightField.getFragments()[0].string();
                productDocument.setProductName(highlightProductName);
            }
        }
        dataMap.put("records",productDocuments);
        return Result.success(dataMap);
    }


}
